package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.HistoricComment;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }

    @Override
    public void deleteBatch(String ids) {

    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {
        CarPackageAudit oldObj = this.get(carPackageAudit.getId());
        oldObj.setInstanceId(carPackageAudit.getInstanceId());
        carPackageAuditMapper.updateByPrimaryKey(oldObj);
    }

    @Override
    public InputStream processImg(Long id) {
        //需要高亮的节点
        //需要高亮的连线
        List<String> highLightedFlows = new ArrayList<>();
        //根据id查询 CarPackageAudit 对象
        CarPackageAudit carPackageAudit = this.get(id);
        // 当前 CarPackageAudit 对象中只有流程实例 id。 根据流程实例 id 查询流程实例对象
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(carPackageAudit.getInstanceId())
                .singleResult();
        // 若已取消的流程图，那我们查看时就默认给其空的高亮节点即可
        if (processInstance == null){
            throw new BusinessException("没有流程实例存在");
        }
        // 获取当前活动的节点 (新方法)
        List<String> highLightedActivities = runtimeService.getActiveActivityIds(processInstance.getId());
        // 根据流程实例获取 流程定义的 Id
        // 流程定义 Id
        String processDefinitionId = processInstance.getProcessDefinitionId();
        // 生成 png 流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return  generator.generateDiagram(bpmnModel,highLightedActivities,highLightedFlows,
                "宋体","宋体","宋体");
    }

    @Override
    public void cancelApply(Long id) {
        //合理化校验 只有审核中的 才可以撤销
        CarPackageAudit carPackageAudit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("只有审核中的流程才可以进行撤销操作");
        }
        //审核记录状态  --> 审核撤销
        carPackageAudit.setStatus(CarPackageAudit.STATUS_CANCEL);
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
        // 通过服务单项id -->找到服务单项对象,把状态改为初始化
        serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        //删除流程实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"撤销流程");
    }

    @Override
    public TablePageInfo<CarPackageAudit> todoQuery(CarPackageAuditQuery qo) {
        BpmnInfo bpmnInfo = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
        //查询 该审核人的所有任务
        long total = taskService.createTaskQuery()
                .processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
                .taskAssignee(ShiroUtils.getUserId().toString())
                .count();
        if (total==0){
            return new TablePageInfo<CarPackageAudit>(total, Collections.EMPTY_LIST);
        }
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
                .taskAssignee(ShiroUtils.getUserId().toString())
                .listPage((qo.getPageNum() - 1) * qo.getPageSize(), qo.getPageSize());
        List<String> businessKeyList = new ArrayList<>();
        //遍历封装成id集合
        for (Task task : taskList) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            businessKeyList.add(processInstance.getBusinessKey());
        }
        //查询数据库
        List<CarPackageAudit> carPackageAuditList =
        carPackageAuditMapper.selectByBusinessKeyList(businessKeyList);
        return new TablePageInfo<>(total,carPackageAuditList);
    }

    @Override
    public void audit(Long id, String auditStatus, String info) {
        // ************************** 任务逻辑 **********************************************
        //只有状态在审核中才可以审批
        CarPackageAudit carPackageAudit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("别瞎几把审批,状态不对!");
        }
        //将同意或者拒绝转换为 Boolean 类型
        Boolean status = Boolean.valueOf(auditStatus);
        //通过流程实例id 查询当前正在活动的任务
        String instanceId = carPackageAudit.getInstanceId();
        Task task = taskService.createTaskQuery()
                .processInstanceId(instanceId)
                .singleResult();
        //设置批注信息
        String msg = ShiroUtils.getUser().getUserName() + (status? "[同意]" : "拒绝") + ",审批意见:" + info;
        //添加批注信息
        taskService.addComment(task.getId(),instanceId,msg);
        //设置流程变量
        // task.getTaskDefinitionKey() 获取到节点在流程图中定义的  id
        String taskDefinitionKey = task.getTaskDefinitionKey();
        Map<String,Object> params = new HashMap<>();
        params.put(taskDefinitionKey,status);
        //完成任务
        taskService.complete(task.getId(),params);
        // ***************************** 审批逻辑 *******************************************
        if (status){
            //审批同意
            //获取下一个任务
            Task nextTask = taskService.createTaskQuery()
                    .processInstanceId(instanceId)
                    .singleResult();
            //判断下一个任务是否存在
            if (nextTask == null){
                //流程实例走完了
                /**
                 *  CarPackageAudit 对象 -->  状态修改为 审批通过   （快照）
                 *  ServiceItem 对象 -->  状态修改为 审核通过   （服务单项）
                 */
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
                serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }
        }else {
            //审批拒绝
            /**
             *  CarPackageAudit 对象 -->  状态修改为 审批拒绝   （快照）
             *  ServiceItem 对象 -->  状态修改为 重新调整   （服务单项）
             */
            // CarPackageAudit 对象 -->  状态修改为 审批拒绝   （快照）
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
            //ServiceItem 对象 -->  状态修改为 重新调整   （服务单项）
            serviceItemService.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }
    }

    @Override
    public TablePageInfo<HistoricComment> listHistory(String instanceId) {
        //获取历史人物
        List<HistoricComment> commentList = new ArrayList<>();
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(instanceId)
                .finished()//已完成人物
                .orderByTaskCreateTime()//按照开始时间排序
                .desc()//倒序排序
                .list();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (HistoricTaskInstance task : taskList) {
                HistoricComment comment = new HistoricComment();
                comment.setTaskName(task.getName());
                comment.setStartTime (sdf.format(task.getStartTime()));
                comment.setEndTime(sdf.format(task.getEndTime()));
                comment.setDurationInMillis(task.getDurationInMillis().toString());
                //拿到每个任务的批注集合
            List<Comment> taskComments = taskService.getTaskComments(task.getId());
            if (taskComments.size()>0){
                //说明存在批注信息
                String fullMessage = taskComments.get(0).getFullMessage();
            }
            commentList.add(comment);

        }
        return new TablePageInfo<HistoricComment>(Long.valueOf(commentList.size()),commentList);
    }

    @Override
    public TablePageInfo<CarPackageAudit> doneQuery(CarPackageAuditQuery qo) {
        BpmnInfo bpmnInfo = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
        //查询 该审核人的所有任务
        long total = historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
                .finished()
                .taskAssignee(ShiroUtils.getUserId().toString())
                .count();
        if (total==0){
            return new TablePageInfo<CarPackageAudit>(total, Collections.EMPTY_LIST);
        }
        List<HistoricTaskInstance> historicTaskInstanceList = historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
                .finished()
                .taskAssignee(ShiroUtils.getUserId().toString())
                .listPage((qo.getPageNum() - 1) * qo.getPageSize(), qo.getPageSize());
        List<String> businessKeyList = new ArrayList<>();
        //遍历封装成id集合
        for (HistoricTaskInstance task : historicTaskInstanceList) {
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            businessKeyList.add(historicProcessInstance.getBusinessKey());
        }
        //查询数据库
        List<CarPackageAudit> carPackageAuditList =
                carPackageAuditMapper.selectByBusinessKeyList(businessKeyList);
        return new TablePageInfo<>(total,carPackageAuditList);
    }
}
